package com.yb.guigu.pick.auth.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yb.guigu.pick.auth.bean.dto.request.SysPermissionAddInfo;
import com.yb.guigu.pick.auth.entity.*;
import com.yb.guigu.pick.auth.mapper.SysRoleMapper;
import com.yb.guigu.pick.auth.mapper.SysRolePermissionMapper;
import com.yb.guigu.pick.core.bean.event.GuiguPickEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/9 15:27
 * FileName: SysUserListener
 * Description:
 */

@Component
@Slf4j
public class SysPermissionListener {


    @Autowired
    SysRoleMapper sysRoleMapper;


    @Autowired
    SysRolePermissionMapper sysRolePermissionMapper;

    @EventListener
    @Async
    public void handle(GuiguPickEvent<SysPermissionAddInfo> event){
        log.info("accept event:{}",event);
        SysPermissionAddInfo sysPermissionAddInfo = event.getData();
        SysPermission sysPermission = sysPermissionAddInfo.getSysPermission();

        SysRole adminRole = getAdminRole();
        SysRolePermission sysRolePermission=new SysRolePermission();
        sysRolePermission.setRoleId(adminRole.getRoleId());
        sysRolePermission.setPermissionId(sysPermission.getPermissionId());
        sysRolePermission.setCreateTime(LocalDateTime.now());
        sysRolePermissionMapper.insert(sysRolePermission);

        log.info("event {} processed",event);
    }


    private SysRole getAdminRole(){

        return sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, "admin")
                .select(SysRole::getId, SysRole::getRoleId));
    }
}
